package cn.xhf.export.core;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


/**
 * @author 统计
 *  ruoyushen
 *
 */
public class ExcelExportUtil {
 private static final String FILEPATH = PathKit.getWebRootPath() + File.separator + "upload" + File.separator ;

	public static String getTitle(){
		Date date = new Date();
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");  
	     String title=FILEPATH+dateFormat.format(date)+"_统计报表.xls";  
	     return title;
	}
	
	
	public static File saveFile(Map<String, String> headData, String sql) {
	     File file = new File(ExcelExportUtil.getTitle());
		// 创建工作�?
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
		// sheet:�?张表的简�?
		// row:表里的行
		// 创建工作薄中的工作表
		HSSFSheet hssfSheet = hssfWorkbook.createSheet();
		hssfSheet.setDefaultColumnWidth(20);
		// 创建�?
		HSSFRow row = hssfSheet.createRow(0);
		// 创建单元格，设置表头 创建�?
		HSSFCell cell = null;
		// 初始化索�?
		int rowIndex = 0;
		int cellIndex = 0;

		// 创建标题�?
		row = hssfSheet.createRow(rowIndex);
		rowIndex++;
		// 遍历标题
		for (String h : headData.keySet()) {
			
			//创建�?
			cell = row.createCell(cellIndex);
			//索引递增
			cellIndex++;
			//逐列插入标题
			cell.setCellValue(headData.get(h));
		}

		// 得到�?有记�? 行：�?
		List<Record> list = Db.find(sql);
		Record record = null;

		if (list != null) {
			// 获取�?有的记录 有多少条记录就创建多少行
			for (int i = 0; i < list.size(); i++) {
				row = hssfSheet.createRow(rowIndex);
				// 得到�?有的�? �?个record就代�? �?�?
				record = list.get(i);
				//下一行索�?
				rowIndex++;
				//刷新新行索引
				cellIndex = 0;
				// 在有�?有的记录基础之上，便利传入进来的表头,再创建N�?
				for (String h : headData.keySet()) {
					cell = row.createCell(cellIndex);
					cellIndex++;
					//按照每条记录匹配数据
					cell.setCellValue(record.get(h) == null ? "" : record.get(h).toString());
				}
			}
		}
		try {
			FileOutputStream fileOutputStreane = new FileOutputStream(file);
			hssfWorkbook.write(fileOutputStreane);
			fileOutputStreane.flush();
			fileOutputStreane.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}
	
    
    /**
             * 导出txt文件
     * @param tileName 
     *
     * @param result
     * @param fileName
     * @return
     */
    @SuppressWarnings("finally")
	public static File writeDataHubDataPro(Map<String, String> tileName, List<Record> result, String fileName) {
        long start = System.currentTimeMillis();
//        String filePath = "D:\\txt";//FILEPATH 相对地址
        StringBuilder content = new StringBuilder();
        Map<String,Object> map = new HashMap<String, Object>();
        boolean flag = false;
        String relFilePath = null;// url
        BufferedWriter out = null;
        FileOutputStream fileOutputStreane = null;
        File file = null;
        try {
            if (result != null && !result.isEmpty() && StringUtils.isNotEmpty(fileName)) {
                fileName += "_" + System.currentTimeMillis() + ".txt";
                File pathFile = new File(FILEPATH);
                if (!pathFile.exists()) {
                    pathFile.mkdirs();
                }
                relFilePath = FILEPATH + File.separator + fileName;
                file = new File(relFilePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));
//                //标题�?
//                out.write("curr_time,link_id,travel_time,speed,reliabilitycode,link_len,adcode,time_stamp,state,public_rec_time,ds");
//                out.newLine();
                for (int i = 0; i < result.size(); i++) {
                	StringBuilder sb = new StringBuilder();
                	for (String str : tileName.keySet()) {
                		sb.append(tileName.get(str)+":"+result.get(i).getColumns().get(str));
                		sb.append(",");
					}
                	out.write(sb.toString());
                	out.newLine();
				}
//                for (String info : result) {
//                    out.write(info);
//                    
//                }
                flag = true;
//                logger.info("写入文件耗时�?*********************************" + (System.currentTimeMillis() - start) + "毫秒");
                System.out.println("写入文件耗时�?*********************************" + (System.currentTimeMillis() - start) + "毫秒");
//				fileOutputStreane = new FileOutputStream(file);
//				fileOutputStreane.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            if (fileOutputStreane !=null) {
//    			try {
//        			fileOutputStreane.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//			}
            map.put("mis", (System.currentTimeMillis() - start) + "毫秒");
//            map.put("type",flag );
//            map.put("url",url+ File.separator +"upload"+ File.separator +fileName);
        }
		return file;
    }
    
    public static void main(String[] args) {
    	try {
        	List<String> list = new ArrayList<String>();
        	list.add("1230");
        	list.add("3450");
        	ExcelExportUtil e = new ExcelExportUtil();
//    		Map b = e.writeDataHubData(list,"我是�?个txt");
//    		System.out.println(b);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
    
    /**  
     * @Description: String类型毫秒数转换成日期        
     * [@param](http://my.oschina.net/param) lo 毫秒�? 
     * @return String yyyy-MM-dd HH:mm:ss    
     */    
     public static String stringToDate(String lo){
       long time = Long.parseLong(lo);
       Date date = new Date(time);
       SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
       return sd.format(date);
     }
    
     /**  
      * @Description: String类型毫秒数转换成日期        
      * [@param](http://my.oschina.net/param) lo 毫秒�? 
      * @return String yyyy-MM-dd HH:mm:ss    
      */    
      public static String stringHMS(String lo){
        long time = Long.parseLong(lo);
        Date date = new Date(time);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(date);
      }
	
}